
import React, { useEffect, useRef, useCallback } from "react";
import { debounce } from "lodash";
import * as echarts from "echarts/core";
import type { EChartsType } from "echarts/core";
import {
  GridComponent,
  LegendComponent,
  MarkLineComponent,
  MarkPointComponent,
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  VisualMapComponent,
  MarkAreaComponent,
} from "echarts/components";
import {
  BarChart,
  LineChart,
  RadarChart,
  PieChart,
  ScatterChart,
} from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";
import { LabelLayout } from "echarts/features";
import { UniversalTransition } from "echarts/features";
// import FullScreenBox from "@/components/FullScreenBox";

echarts.use([
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  MarkLineComponent,
  MarkPointComponent,
  BarChart,
  GridComponent,
  LineChart,
  UniversalTransition,
  RadarChart,
  CanvasRenderer,
  VisualMapComponent,
  MarkAreaComponent,
  PieChart,
  ScatterChart,
  LabelLayout,
]);

interface IProps {
  options: any;
  theme: ThemeType;
}

const ChatBIChart: React.FC<IProps> = ({ options, theme }) => {
  // Component State
  const echartsRef = useRef<HTMLDivElement | null>(null);
  const myChartRef = useRef<EChartsType | null>(null);
  const setCharts = () => {
    if (!options) return;
    if (myChartRef.current) {
      myChartRef.current.clear();
      myChartRef.current.resize();
    } else {
      myChartRef.current = echarts.init(echartsRef.current, theme);
    }
    myChartRef.current.setOption(options);
  };
  const onResize = useCallback(
    debounce(() => {
      if (myChartRef.current) {
        myChartRef.current.resize();
      }
    }, 100),
    []
  );
  // Component Effect
  useEffect(() => {
    setCharts();
  }, [options]);
  useEffect(() => {
    const resizeObserver = new ResizeObserver((entries) => {
      for (let entry of entries) {
        onResize();
      }
    });
    if (echartsRef.current) {
      resizeObserver.observe(echartsRef.current);
    }
    return () => {
      resizeObserver.disconnect();
    };
  }, []);
  return (
    <div
    // resize={onResize}
    >
      <div className="chat-bi-chart" ref={echartsRef}></div>
    </div>
  );
};

export default ChatBIChart;
